package org.example.rest;

import javafx.concurrent.Worker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @description: Semaphore 信号量
 * @author: yh
 * @date: 2023/1/1
 */

@RestController
@RequestMapping(value = "/semaphore")
public class SemaphoreController {

    public static void main(String[] args) {
        // 停车场车位数量
        Semaphore semaphore = new Semaphore(5);

        for (int i = 1; i <= 10; i++) {
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "进入停车场");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                    System.out.println(Thread.currentThread().getName() + "驶离停车场");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }
            }, i + "号车");
            thread.start();
        }
    }
}
